package com.example.qxfw.nyqx.controller;

import com.example.qxfw.common.SysResult;
import com.example.qxfw.common.entity.ny.CropyieldFcst;
import com.example.qxfw.common.entity.ny.StationInfo;
import com.example.qxfw.nyqx.dto.NyClDto;
import com.example.qxfw.nyqx.service.CropGrowdateIndexlibService;
import com.example.qxfw.nyqx.service.CropyieldFcstService;
import com.example.qxfw.nyqx.service.DevelopmentPeriodPredictionService;
import com.example.qxfw.nyqx.service.YieldForecastService;
import com.example.qxfw.nyqx.vo.CropYieldFcstListVo;
import com.example.qxfw.nyqx.vo.CropYieldHistoryListVo;
import com.example.qxfw.common.util.DateUtil;
import com.example.qxfw.rcyw.service.StationInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

@Api(tags = "农气预报-产量预报")
@RestController
@CrossOrigin
@RequestMapping("/YieldForecastController")
public class YieldForecastController {

    @Value("${filePath.active}")
    private String active;

    @Autowired
    private YieldForecastService yieldForecastService;

    @Autowired
    private StationInfoService stationInfoService;

    @Autowired
    private CropGrowdateIndexlibService cropGrowdateIndexlibService;

    @Autowired
    private DevelopmentPeriodPredictionService developmentPeriodPredictionService;


    @ApiOperation("获取作物名称")
    @GetMapping("/getGrowDateCropName")
    public SysResult getGrowDateCropName() {
        List<String> cropName = cropGrowdateIndexlibService.getCropName();
        return SysResult.success(cropName);
    }

    @ApiOperation("根据作物名称获取种类")
    @GetMapping("/getGrowDateCropType")
    public SysResult getGrowDateCropType(String cropName) {
        List<String> type = cropGrowdateIndexlibService.getType(cropName);
        return SysResult.success(type);
    }

    @ApiOperation("预报查询-获取预报列表数据")
    @GetMapping("/getYbList")
    public SysResult getYbList(String cropName, String type, String year) {
        List<CropYieldFcstListVo> yieldFcstListVos = yieldForecastService.listYieldFcst(year, cropName, type);
        for (CropYieldFcstListVo fcst : yieldFcstListVos) {
            StationInfo info = stationInfoService.getById(fcst.getStationid());
            fcst.setStationname(info.getStationname());
        }
        return SysResult.success(yieldFcstListVos);
    }

    @ApiOperation("获取农服站点")
    @GetMapping("/getAgriStation")
    public SysResult getAgriStation(String mainCrop) {
        List<StationInfo> stationInfos = developmentPeriodPredictionService.listByMainCrop(mainCrop);
        return SysResult.success(stationInfos);
    }

    @ApiOperation("计算晚稻模型产量")
    @GetMapping("/calculate")
    public SysResult calculate(long year, String stationId, String type) {
        NyClDto calculate = yieldForecastService.calculate(year, stationId, type);
        return SysResult.success(calculate);
    }

    @ApiOperation("计算早稻模型产量")
    @GetMapping("/earlycalculate")
    public SysResult earlycalculate(long year, String stationId, String type, String sunhour) {
        NyClDto calculate = yieldForecastService.earlycalculate(year, stationId, type, sunhour);
        return SysResult.success(calculate);
    }

    @ApiOperation("产量预报制作")
    @GetMapping("/ybzz")
    public SysResult ybzz(double qxCl, double qsCl, double sjCl, String cropName, String stationId, long year, String type) {
        double yield = yieldForecastService.ybzz(qxCl, qsCl, sjCl, cropName, stationId, year, type);
        return SysResult.success(yield);
    }

    @ApiOperation("获取产量预报列表")
    @GetMapping("/getFcstList")
    public SysResult getFcstList(long year1, long year2, String stationId, String type, String cropName) {
        List<CropYieldFcstListVo> cropYieldFcstListVos = yieldForecastService.listYieldFcstVo(year1, year2, stationId, type, cropName);
        return SysResult.success(cropYieldFcstListVos);
    }

    @ApiOperation("获取产量历史列表")
    @GetMapping("/getHistoryList")
    public SysResult getHistoryList(long year1, long year2, String stationId, String type, String cropName) {
        List<CropYieldHistoryListVo> cropYieldHistoryListVos = yieldForecastService.listYieldHistoryVo(year1, year2, stationId, type, cropName);
        return SysResult.success(cropYieldHistoryListVos);
    }

    /************************
     * @Author : HuangDeYin Jolly
     * @Description :
     * @param stationName:站点名称
     * @param maker:制作人
     * @param type :类型
     * @param breed :品种
     * @param YW :气象产量
     * @param YT :趋势产量
     * @param YQ :随机产量
     ************************/
    @RequestMapping(value = "GenerateDocument",method = RequestMethod.GET)
    @ApiOperation("生成docx")
    public Object GenerateDocument(String stationName, String maker, String type, String breed, Integer YW, Integer YT, Integer YQ) {
        // 获取当前日期和时间
        LocalDateTime currentDateTime = LocalDateTime.now();
        // 设置时间部分为00:00:00
        LocalDateTime midnight = currentDateTime.with(LocalTime.MIDNIGHT);
        //预报时间
        Timestamp forecastTime = DateUtil.localDateTimeToTimestamp(midnight);
        //文档制作时间
        Timestamp makeTime = DateUtil.localDateTimeToTimestamp(currentDateTime);
        return yieldForecastService.generateDocument(stationName, forecastTime, makeTime, maker, type, breed, YW, YT, YQ);
    }


    @ApiOperation("获取产品模板")
    @GetMapping("/getTemplate")
    public Object getTemplate() {
        //模板路径
        String templatePath;
        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        if (active.equals("dev")) {
            templatePath = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() +
                    "\\src\\main\\resources\\templates\\yieldForecastTemp\\晚稻产量预报.docx";
        } else {
            templatePath = applicationHome.getSource().getParentFile() +
                    "\\resource\\templates\\yieldForecastTemp\\晚稻产量预报.docx";
        }
        // 设置前端响应
        byte[] buffer = new byte[1024];
        int bytesRead;
        try (
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                FileInputStream inputStream = new FileInputStream(templatePath);
        ) {
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }
            byte[] byteArray = byteArrayOutputStream.toByteArray();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentDispositionFormData("attachment", "发育期预报.docx");
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentLength(byteArray.length);
            return new ResponseEntity<>(byteArray, headers, HttpStatus.OK);
        } catch (Exception e) {
            System.err.println("模板下载失败");
        }
        return null;
    }


}
